<template>
  <div class="report-content-wrapper">
    <!-- 报告摘要 -->
    <div class="report-summary">
      <div class="summary-title" @click="toggleSummary">
        报告摘要
        <span class="collapse-icon">
          <down-outlined v-if="summaryCollapsed" />
          <up-outlined v-else />
        </span>
      </div>
      <div v-if="detectionReport?.summary" class="summary-content markdown-content" v-show="!summaryCollapsed">
        <div v-html="renderMarkdown(detectionReport.summary)"></div>
      </div>
      <a-empty v-else-if="!summaryCollapsed" description="暂无摘要信息，请先进行报告总结" />
    </div>

    <!-- 对话列表 -->
    <a-card :bordered="false" style="margin-top: 20px;">
      <div class="chat-container">
        <div class="messages-container" ref="messagesContainer">
          <!-- 使用MessageList组件 -->
          <message-list :records="questionRecords" />
        </div>

        <!-- 输入框部分 -->
        <div class="input-container">
          <a-textarea v-model:value="inputMessage" :rows="3" placeholder="请输入您的问题..."
            :disabled="!detectionReport?.summary" @keypress.enter.prevent="handleSendMessage" />
          <a-button type="primary" :loading="sending" :disabled="!inputMessage.trim() || !detectionReport?.summary"
            @click="handleSendMessage" style="margin-top: 8px;">
            发送
          </a-button>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue'
import { getQuestionRecords, type QuestionRecord, askDocumentSSE, type AskDocumentResponse } from '@/api/chat'
import type { DetectionReport } from '@/api/documents'
import MarkdownIt from 'markdown-it'
import MessageList from './MessageList.vue'

const props = defineProps<{
  detectionReport: DetectionReport | null
}>()

const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  breaks: true
})

const questionRecords = ref<QuestionRecord[]>([])
const inputMessage = ref('')
const sending = ref(false)
const messagesContainer = ref<HTMLElement | null>(null)
const summaryCollapsed = ref(false)

// 切换摘要的折叠状态
const toggleSummary = () => {
  summaryCollapsed.value = !summaryCollapsed.value
}

// Markdown渲染函数
const renderMarkdown = (content: string): string => {
  if (!content) return ''
  return md.render(content)
}

// 格式化日期时间函数
const formatDateTime = (dateTimeStr: string): string => {
  if (!dateTimeStr) return '';
  try {
    const date = new Date(dateTimeStr);
    return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateTimeStr;
  }
}

// 补零函数
const padZero = (num: number): string => {
  return num < 10 ? `0${num}` : `${num}`;
}

// 获取提问记录
const fetchQuestionRecords = async () => {
  if (!props.detectionReport?.id) return
  try {
    const response = await getQuestionRecords({ detection_report_id: props.detectionReport.id })
    console.log('response = ', response)
    questionRecords.value = response
  } catch (error) {
    console.error('获取提问记录失败:', error)
    message.error('获取提问记录失败')
  }
}

// 发送消息
const handleSendMessage = async () => {
  if (!props.detectionReport?.id || !inputMessage.value.trim()) return

  sending.value = true
  try {
    // 创建一个临时记录用于显示
    const tempRecord: QuestionRecord = {
      id: Date.now(), // 临时ID
      question: inputMessage.value.trim(),
      answer: '',
      knowledge_entries: null,
      used_knowledge_entries: null,
      recommended_questions: null,
      question_time: new Date().toISOString(),
      answer_time: null,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
      detection_report_id: props.detectionReport.id
    };

    // 添加到记录列表
    questionRecords.value = [...questionRecords.value, tempRecord];

    // 保存问题内容并清空输入框
    const questionText = inputMessage.value.trim();
    inputMessage.value = '';

    // 滚动到底部
    await scrollToBottom();

    // 使用SSE API发送请求
    askDocumentSSE(
      props.detectionReport.id,
      questionText,
      (chunk: AskDocumentResponse) => {
        // 更新最后一条记录的回答内容
        if (questionRecords.value.length > 0) {
          const lastRecord = questionRecords.value[questionRecords.value.length - 1];
          lastRecord.answer = (lastRecord.answer || '') + chunk.content;
          questionRecords.value = [...questionRecords.value];

          // 更新时间
          lastRecord.answer_time = new Date().toISOString();
          lastRecord.updated_at = new Date().toISOString();

          // 滚动到底部
          scrollToBottom();
        }
      },
      (data: AskDocumentResponse) => {
        // 回答完成后获取最新的聊天记录
        fetchQuestionRecords();
      }
    );
  } catch (error: any) {
    console.error('发送消息失败:', error);
    message.error(error.response?.data?.error || '发送消息失败');
  } finally {
    sending.value = false;
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 监听document变化，获取提问记录
watch(() => props.detectionReport?.id, (newId) => {
  if (newId) {
    fetchQuestionRecords()
  }
})
</script>

<style scoped>
.report-summary {
  margin-bottom: 20px;
  background-color: #fafafa;
  border-radius: 4px;
  padding: 0 0 12px 0;
}

.summary-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  font-weight: 500;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.collapse-icon {
  margin-left: 8px;
  font-size: 12px;
  color: #999;
}

.summary-content {
  padding: 16px;
  background-color: #fff;
  border-radius: 0 0 4px 4px;
}

.report-content {
  padding: 12px;
  background-color: #fff;
  /* overflow-y: auto; */
  /* max-height: 600px; */
  border-radius: 4px;
}

.report-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* Markdown样式 */
.markdown-content {
  line-height: 1.6;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content h1 {
  font-size: 2em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.markdown-content h2 {
  font-size: 1.5em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.markdown-content h3 {
  font-size: 1.25em;
}

.markdown-content h4 {
  font-size: 1em;
}

.markdown-content p {
  margin-top: 0;
  margin-bottom: 16px;
}

.markdown-content blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin: 0 0 16px 0;
}

.markdown-content ul,
.markdown-content ol {
  padding-left: 2em;
  margin-bottom: 16px;
}

.markdown-content code {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27, 31, 35, 0.05);
  border-radius: 3px;
  font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
}

.markdown-content pre {
  padding: 16px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  background-color: #f6f8fa;
  border-radius: 3px;
}

.markdown-content pre code {
  background-color: transparent;
  padding: 0;
}

.markdown-content table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 16px;
}

.markdown-content table th,
.markdown-content table td {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

.markdown-content table tr {
  background-color: #fff;
  border-top: 1px solid #c6cbd1;
}

.markdown-content table tr:nth-child(2n) {
  background-color: #f6f8fa;
}

.chat-container {
  display: flex;
  flex-direction: column;
  /* height: 600px; */
}

.messages-container {
  flex: 1;
  /* overflow-y: auto; */
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 16px;
}

.message {
  margin-bottom: 16px;
}

.message-content {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.message-avatar {
  flex-shrink: 0;
}

.message-text {
  flex: 1;
  padding: 12px;
  border-radius: 8px;
  max-width: 80%;
}

.user-message .message-content {
  flex-direction: row-reverse;
}

.user-message .message-text {
  background-color: #1890ff;
  color: white;
}

.assistant-message .message-text {
  background-color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.input-container {
  padding: 16px;
  background-color: white;
  border-top: 1px solid #f0f0f0;
}

.question-records-container {
  margin-bottom: 16px;
}

.question-records-title {
  font-weight: 500;
  margin-bottom: 8px;
}

.question-records-list {
  /* max-height: 300px; */
  /* overflow-y: auto; */
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 16px;
}

.user-message-text {
  background-color: #1890ff;
  color: white;
}

.assistant-message-text {
  background-color: white;
}
</style>